import { app, BrowserWindow, screen, globalShortcut, shell } from "electron";
import { CustomScheme } from "./CustomScheme";
import { CommonWindowEvent } from "./CommonWindowEvent";
import { startExpressServer, stopExpressServer ,createUploadDirectory} from "./ExpressServer";
import * as path from "path";
import { createFileStorage } from "./FileStorage";

process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = "true";
createUploadDirectory(process.env.NODE_ENV);
createFileStorage();



let mainWindow: BrowserWindow;

// 添加单实例检查
const isSingleInstance = app.requestSingleInstanceLock();
if (!isSingleInstance) {
  app.quit();
  process.exit(0);
}

app.on("second-instance", () => {
  if (mainWindow) {
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.focus();
  }
});

app.whenReady().then(() => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  let config = {
    width: Math.floor(width * 0.8), // 屏幕宽度的 80%
    height: Math.floor(height * 0.8), // 屏幕高度的 80%
    icon: path.join(__dirname, "../../build/icons/icon.ico"),
    webPreferences: {
      nodeIntegration: true,
      webSecurity: false,
      allowRunningInsecureContent: true,
      contextIsolation: false,
      webviewTag: true,
      spellcheck: false,
      disableHtmlFullscreenWindowResize: true,
      show: false,
    },
    frame: false,
  };
  mainWindow = new BrowserWindow(config);
  // mainWindow.webContents.openDevTools({ mode: "undocked" });
  if (process.argv[2]) {
    mainWindow.loadURL(process.argv[2]);
  } else {
    CustomScheme.registerScheme();
    mainWindow.loadURL(`app://index.html`);
  }

  mainWindow.once("ready-to-show", () => {
    mainWindow.show();
    // 打开外部链接使用默认浏览器
    mainWindow.webContents.setWindowOpenHandler(({ url }) => {
      shell.openExternal(url);
      return { action: "deny" };
    });
  });

  CommonWindowEvent.listen();
  CommonWindowEvent.regWinEvent(mainWindow);

  try {
    startExpressServer();
  } catch (error) {
    console.log(error);
  }

  globalShortcut.register("ctrl+shift+c", () => {
    BrowserWindow?.getFocusedWindow()?.webContents.openDevTools();
    console.log("Pressed ctrl+shift+c");
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("before-quit", () => {
  stopExpressServer(); // 关闭 Express 服务
});
